import { get } from '@utils/request'
import { store } from '../store'

/**
 * 获取七牛配置
 */
export async function getQiniuConfig() {
  let qiniuConfig = store.getState().app.qiniuConfig
  if (JSON.stringify(qiniuConfig) !== '{}') return qiniuConfig

  const { data } = await get('/weapp/common/upsetting')
  qiniuConfig = data
  store.dispatch({ type: 'SET_QINIU_CONFIG', qiniuConfig })
  return qiniuConfig
}

/**
 * 获取七牛上传token
 * @returns
 */
export async function getUploadToken() {
  const { data: { uptoken } } = await get('/weapp/common/uptoken')
  return uptoken
}

/**
 * options: { file: '文件路径', key: '文件名', basePath: '拼接路径' }
 * @param {*} filePath
 * @param {*} options
 * @param {*} success
 * @param {*} fail
 * @param {*} progress
 * @param {*} cancelTask
 * @param {*} before
 * @param {*} complete
 */
export async function doUpload(file, key = null, basePath = null) {
  const qiniuConfig = await getQiniuConfig()
  const token = await getUploadToken()
  // 表单参数处理
  let fileName = file.split('//')[1]
  if (key) fileName = key
  const formData = { token }
  if (basePath) formData.key = basePath + '/' + fileName

  return new Promise((resolve, reject) => {
    wx.uploadFile({
      url: qiniuConfig.uploadUrl,
      filePath: file,
      name: 'file',
      formData: formData,
      success({ data }) {
        try {
          var dataObject = JSON.parse(data)
          dataObject.fileUrl = qiniuConfig.cdnhost + '/' + dataObject.key
          resolve(dataObject)
        } catch (e) {
          console.error('七牛上传解析失败：', data)
          reject(e)
        }
      },
      fail(error) {
        console.error(error)
        reject(error)
      }
    })
  })
}
